<?php

require_once(__DIR__."/PI/all.inc.php");

class AccountController extends \PI\ModelController{
    public $dbset;
    function __construct(\PI\Database $db)
    {
        parent::__construct($db);
    }
}

class AccountControllerxxx extends \PI\Controller{
    public $dbset;
    function __construct(\PI\Database $db)
    {
        $this->dbset = $db->dbset("Account");
    }

    

    function list(AccountListViewModel $vm){
        $perm = $this->check_permission($this->user,"list",$vm);
        if(!$perm) return $this->error("permission","没有访问权限",$vm);
        $vm->fill($this->dbset,$this->make_listWhere($this->dbset,$vm,$perm));
        return $vm;

    }
    

    function new(AccountViewModel $vm){
        $perm = $this->check_permission($this->user,"list",$vm);
        if(!$perm) return $this->error("permission","没有访问权限",$vm);

        if(!$vm || !$vm->Id){
            return $vm;
        }else {
            if(!$vm->validate(null,null)) return $vm;
            $this->dbset->add($vm);
            return $vm;
        }
    }

    function detail($id){
        $perm = $this->check_permission($this->user,"list",null,$id);
        if(!$perm) return $this->error("permission","没有访问权限",null);

        $vm = new AccountViewModel();
        $this->dbset->load($id)->to_object($vm);
        return $vm;
    }
    function modify(AccountViewModel $vm,$id){
        $perm = $this->check_permission($this->user,"list",$vm,$id);
        if(!$perm) return $this->error("permission","没有访问权限",$vm);

        if(!$vm){
            $this->dbset->load($id)->to_object($vm);
            return $vm;
        }else {
            $vm->set_id($id);
            $this->dbset->save($vm);
            return $vm;
        }
    }

    function delete($id){
        $perm = $this->check_permission($this->user,"list",null,$id);
        if(!$perm) return $this->error("permission","没有访问权限",$id);
    }

    protected function check_permission(User $user,string $action,$data,$id=null):\PI\Permission{
        return new \PI\Permission();
    }
    protected function make_listWhere(\PI\DbSet $dbset,AccountListViewModel $vm,\PI\Permission $perm=null):\PI\WhereBuilder{
        $builder = new \PI\WhereBuilder($vm,$perm,null);
        $builder->contains("Username")->contains("Code");
        return $builder;
    }
}

class AccountViewModel extends \PI\ViewModel{
    public $Id;
    public $Username;
    public $Password;
    public $Code;
    public $CreateTime;
    public $UpdateTime;
    
    function validate(array $allows=null,array $denies=null):bool{
        return true;
    }
}

class AccountListViewModel extends \PI\ListViewModel{
    public $Username;
    public $Code;
}